package my.diplom.web.validators;

import org.springframework.validation.Validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.apache.log4j.Logger;
import my.diplom.entity.User;
import my.diplom.dao.service.UserService;
import my.diplom.exceptions.UserNotFoundException;

/**
 * Created by IntelliJ IDEA.
 * User: gb
 * Date: 21.06.2009
 * Time: 21:41:59
 * To change this template use File | Settings | File Templates.
 */
public class RegisterValidator implements Validator{

     private static final Logger log = Logger.getLogger(RegisterValidator.class);
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public boolean supports(Class clazz) {
        return User.class.equals(clazz);
    }

    public void validate(Object target, Errors errors) {
        User user = (User) target;
        if (user == null) errors.reject("Null data received");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "firstName.empty", "First name is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "lastName.empty", "Last name is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "login.empty", "Login is reqired!" );
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email.empty", "Email is reqired!" );
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.empty", "Password is reqired!" );

        String password = user.getPassword();
        if (password == null || password.length() < 5 * 2) errors.rejectValue("password", "wrong.passwords", "Wrong password length!");

        String p1 = password.substring(0, password.length() / 2);
        String p2 = password.substring(password.length() / 2 + 1, password.length());
        if (! p1.equals(p2)) errors.rejectValue("password", "mismatch.passwords", "Mismatch passwords!");


        User u = null;
        try {
            u = userService.getByLogin(user.getLogin());
        } catch (UserNotFoundException e) {
            e.printStackTrace();
        }

        if (u != null) errors.rejectValue("login", "login.exists", "login exists already" );

        user.setPassword(p1);


    }
}
